<template>
  <scroller scroll-direction="horizontal" show-scrollbar="false" class="scrollbar">
    <div class="scrollbar">
      <div @click="itemClick" v-for="(item, i) in itemList"
           v-bind:key="i"
           :ref="'item'+i" :idx="i">
        <text :style="{color: i === selectedIdx ? colorStyleMap[colorStyle].selectedColor : colorStyleMap[colorStyle].color,
                borderBottomColor: i === selectedIdx ? colorStyleMap[colorStyle].line : 'transparent'}"
              :class="['scrollbar-item-text']">{{item.title}}</text>
      </div>
    </div>
  </scroller>
</template>

<script>
let dom = weex.requireModule('dom')
let theme = require('../include/theme')
let offsetAddon = 60
let COLOR_STYLE = {
  light: {
    color: '#fff',
    line: '#fde85a',
    selectedColor: '#fde85a'
  },
  default: {
    color: theme.color.default,
    selectedColor: theme.color.primary,
    line: theme.brand.primary
  }
}
module.exports = {
  props: {
    itemList: {default: []},
    colorStyle: {default: 'default'}
  },
  data () {
    return {
      selectedIdx: 0,
      colorStyleMap: COLOR_STYLE
    }
  },
  created () {
  },
  methods: {
    itemClick (event) {
      this.selectedIdx = event.target.attr.idx
      let itemRef = this.$refs['item' + this.selectedIdx]
      dom.getComponentRect(itemRef[0], rs => {
        let left = rs.size.left
        let width = rs.size.width
        let shouldBeLeft = null
        if (left - offsetAddon < 0) {
          shouldBeLeft = offsetAddon
        } else if (left + width + offsetAddon > 750) {
          shouldBeLeft = 750 - width - offsetAddon
        }
        if (this.selectedIdx === 0) {
          shouldBeLeft = 0
        }
        if (shouldBeLeft !== null) {
          dom.scrollToElement(itemRef[0], {offset: -shouldBeLeft})
        }
      })
      this.$emit('click', this.selectedIdx)
    }
  }
}
</script>

<style lang="scss">
  @import "../sass/var";
  @import "../sass/mixin";

  $height: 75px;
  .scrollbar {
    flex-direction: row;
    height: $height;
    line-height: $height;
    @include border-bottom(1px, solid, #ddd);
    &-item {
      padding: 0;
      height: $height;
      transition-property: color, transform;
      transition-duration: .6s;
      transition-timing-function: ease;
      transform-origin: center center;
      align-items: center;
      justify-content: center;
      &-text {
        color: $color;
        font-size: 30px;
        margin: 0 20px;
        height: $height;
        line-height: $height;
        @include border-bottom(4px, solid, transparent);
      }
      &-selected {
        &-text {
          color: $color-primary;
          @include border-bottom(4px, solid, $color-primary);
        }
      }
    }
  }
</style>
